﻿using System.Windows.Interactivity;
using Microsoft.Phone.Controls;

namespace BlogApp.WP8.Utils
{
    public class IncrementalLoadingTrigger : TriggerBase<LongListSelector>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.ItemRealized += OnItemRealized;
        }

        private void OnItemRealized(object sender, ItemRealizationEventArgs e)
        {
            var longListSelector = sender as LongListSelector;
            if (longListSelector == null)
            {
                return;
            }

            var item = e.Container.Content;
            var items = longListSelector.ItemsSource;
            var index = items.IndexOf(item);

            if (items.Count - index <= 1)
            {
                InvokeActions(null);
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.ItemRealized -= OnItemRealized;
        }
    }
}